<template>
  <div style="height: 100vh;">
    <el-header style="height: 6vh;">
    </el-header>
    <div>
      <!--      height: 631px;-->
      <el-container style="height: 94vh; border: 1px solid #ededed;overflow:scroll">
        <el-aside style="border: 1px solid #ededed;">
          <el-tree node-key="id" :data="data" :props="defaultProps" :default-expanded-keys="expandedKeys"
                   @node-click="handleNodeClick" :highlight-current="true">
            <template slot-scope="{ node }">
              <span class="span-ellipsis" :title="node.label">{{ node.label }}</span>
            </template>
          </el-tree>
        </el-aside>


        <el-container>
          <!--          视频播放-->
          <div v-if="VideoVisible">
            <video ref="myVideo" width="94%" controls>
              <source :src="url" type="video/mp4">
              您的浏览器不支持视频标签。
            </video>
          </div>
          <!--          pdf播放-->
          <div v-if="type">
            <iframe :src="url" style="width: 1000px;height: 500px"></iframe>
          </div>
          <!--          考试-->
          <div v-if="testVisible">
            <div>
              <el-card
                  v-for="question in testQuestionList"
                  :key="question.id"
                  style="width: 600px;margin-bottom: 5px"
                  :ref="`card-${question.id}`"
                  shadow="hover"

              >
                <div slot="header" class="clearfix">
                  <span>题目{{ question.code }}：{{ question.question }}</span>
                </div>
                <div v-if="question.type === '单选' || question.type === '多选'" class="radio-group">
                  <el-radio-group v-model="ans[question.id]" v-if="question.type === '单选'"
                                  @change="handleChange(question)">
                    <el-radio :label="'A'">A：{{ question.a }}</el-radio>
                    <el-radio :label="'B'">B：{{ question.b }}</el-radio>
                    <el-radio :label="'C'">C：{{ question.c }}</el-radio>
                    <el-radio :label="'D'">D：{{ question.d }}</el-radio>
                  </el-radio-group>

                  <el-checkbox-group v-model="ans[question.id]" v-if="question.type === '多选'" class="checkbox-group"
                                     @change="handleChange(question)">
                    <el-checkbox :label="'A'">A：{{ question.a }}</el-checkbox>
                    <el-checkbox :label="'B'">B：{{ question.b }}</el-checkbox>
                    <el-checkbox :label="'C'">C：{{ question.c }}</el-checkbox>
                    <el-checkbox :label="'D'">D：{{ question.d }}</el-checkbox>
                  </el-checkbox-group>
                </div>
                <div v-if="question.type === '判断'">
                  <el-radio-group v-model="ans[question.id]" @change="handleChange(question)">
                    <el-radio :label="'对'">正确</el-radio>
                    <el-radio :label="'错'">错误</el-radio>
                  </el-radio-group>
                </div>

              </el-card>

            </div>
          </div>

          <div style="position: absolute;top: 10vh;right: 10vh" v-if="testVisible">
            <span v-for="(question, index) in testQuestionList" :key="question.id">
              <el-button @click="scrollToCard(question.id)" :type="click[question.id] ? 'primary' : 'default'"
                         style="margin-right: 5px;margin-bottom: 2px;float: left;">
               <span> {{ question.code }}</span>
              </el-button>
              <br v-show="index%4===0&&index>0">
            </span>
            <div>
              <el-button style="margin-top: 50px;float: left;" type="danger" @click="validateAnswers"
                         v-if="testVisible">交卷
              </el-button>
            </div>
          </div>

          <h1 v-show="myScoreVisible" style="margin-left: 400px;margin-top: 300px">{{ myScore }}</h1>
        </el-container>


      </el-container>


    </div>


  </div>


</template>
<script>


import {getDocumentVideo} from "@/api/documentVideo";
import {addVideoLearningRecords, getVideoLearningRecords} from "@/api/videoLearningRecords";
import da from "element-ui/src/locale/lang/da";
import {getTestQuestionListForTest, selectedQuestionAndScore} from "@/api/testPaper";
import {addScore} from "@/api/Score";
import {addLearningSituation} from "@/api/learningSituation";

export default {
  data() {
    return {
      data: [
        {
          id: 1,
          label: '视频',
          children: []
        },
        {
          id: 2,
          label: '文档',
          children: []
        },
        {
          id: 3,
          label: '考试',
          children: []
        }
      ],
      defaultProps: {
        id: 'id',
        children: 'children',
        label: 'label'
      },
      expandedKeys: [], // 初始时不展开任何节点

      trainingPlanId: 1,
      url: '',
      VideoVisible: false,
      documentVideo: {},
      type: false,
      testVisible: false,
      testQuestionList: [],
      //考试：
      selectedOfOne: '',
      selectedOfMore: [],
      ans: {},//存储所有答案
      selectedAnswers: {},
      click: [],//判断试题是否做
      myScore: '',
      myScoreVisible: false,
    };
  },

  methods: {
    getDocumentVideos() {
      var searchParams = new URLSearchParams(window.location.search);
      var trainPlanId = searchParams.get('trainPlanId');
      this.trainingPlanId = parseInt(trainPlanId, 10);
      getDocumentVideo(this.trainingPlanId, false).then((res) => {
        console.log(res)
        if (res.data.code === 1) {
          this.documentVideos = res.data.data;
          this.documentVideos.forEach(resource => {
            // 判断资源类型
            if (resource.url.endsWith('.mp4') || resource.url.endsWith('.mov') || resource.url.endsWith('.avi')) {
              // 视频类型
              this.data[0].children.push({
                id: resource.id,
                label: resource.name,
                url: resource.url
              });
            } else {
              // 其他类型，可以放入考试或其他分类
              this.data[1].children.push({
                id: resource.id,
                label: resource.name,
                url: resource.url
              });
            }
          });
          //跳转版本返回优化
          //this.expandTreeNode(11);
          // 获取当前URL的查询参数
          //var searchParams = new URLSearchParams(window.location.search);
          //var treeNodeId = parseInt(searchParams.get('treeNodeId'), 10);//必须数字，666
          //console.log('treeNodeId',treeNodeId)
          //this.expandTreeNode(treeNodeId);
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch((e) => {
      })
    },
    handleNodeClick(data) {
      if (data.id === 3) {
        //试卷
        this.type = false;
        this.VideoVisible = false;
        this.getTestQuestionsListForTest();
        return;
      }

      // 添加自定义文字到查询参数
      console.log(data);
      if (data.url == null) {
        return
      }
      this.documentVideo.id = data.id;
      this.documentVideo.name = data.name;
      this.documentVideo.url = data.url;

      this.VideoVisible = false;
      this.testVisible = false;
      this.myScoreVisible = false;
      this.type = false;

      if (data.url.endsWith('.mp4') || data.url.endsWith('.mov') || data.url.endsWith('.avi')) {
        this.url = data.url;
        //确保数据存在
        this.$nextTick(() => {
          this.VideoVisible = true;
          this.$nextTick(() => {
            this.initVideoPlayer();
          });
        });
      }
          //跳转版本
          /*else if (data.url.endsWith('.pdf')) {
            // 获取当前URL的查询参数
            var searchParams = new URLSearchParams(window.location.search);
            var trainPlanId = searchParams.get('trainPlanId'); // 获取treeNodeId参数
            //浏览pdf
            window.location.href = 'http://localhost:8081/pdfjs-4.9.155-dist/web/viewer.html?file='
                + data.url +"&trainPlanId="+trainPlanId+ "&treeNodeId="+data.id;
          }*/
      //不跳转版本
      else if (data.url.endsWith('.pdf')) {
        //浏览pdf
        this.url = 'http://localhost:8081/pdfjs-4.9.155-dist/web/viewer.html?file=' + data.url;
        this.type = true;
        addLearningSituation(this.trainingPlanId, this.documentVideo.id, 100).then((res) => {
        }).catch((e) => {
        })

      } else {
        addLearningSituation(this.trainingPlanId, this.documentVideo.id, 100).then((res) => {
        }).catch((e) => {
        })
        window.open(data.url, '_blank');
      }

    },
    /*expandTreeNode(treeNodeId) {
      // 设置特定的树节点展开
      this.expandedKeys = [treeNodeId];
    },*/


    //视频监视
    initVideoPlayer() {
      const video = this.$refs.myVideo;
      if (video) {
        /* video.addEventListener('pause', () => {
           console.log(`视频已暂停，当前播放到的时间是：${video.currentTime}秒`);
         });*/
        video.addEventListener('loadedmetadata', () => {
          /* const savedTime = localStorage.getItem('videoTime');
           if (savedTime) {
             video.currentTime = parseFloat(savedTime);
           }*/
          var searchParams = new URLSearchParams(window.location.search);
          var trainPlanId = searchParams.get('trainPlanId');
          //设置开始时间
          getVideoLearningRecords(trainPlanId, this.documentVideo.id).then((res) => {
            console.log(res);
            if (res.data.code === 1) {
              video.currentTime = parseFloat(res.data.data);
            } else {
              console.log("暂无记录或查询失败")
            }
          }).catch((e) => {
          })
        });

        video.addEventListener('pause', () => {
          //localStorage.setItem('videoTime', video.currentTime);
          console.log(`视频已暂停，当前播放到的时间是：${video.currentTime}秒`);
          //切换或者播放完毕以及暂停，均会触发
          var searchParams = new URLSearchParams(window.location.search);
          var trainPlanId = searchParams.get('trainPlanId');
          let time = Math.floor(video.currentTime);
          addVideoLearningRecords(trainPlanId, this.documentVideo.id, time).then((res) => {
            if (res.data.code === 1) {
              //console.log("记录成功");
            } else {
              console.log(res.data.msg);
            }
          }).catch((e) => {
          })
          let playbackPercentage = Math.floor((video.currentTime / video.duration) * 100);
          //console.log("playbackPercentage",playbackPercentage)
          addLearningSituation(this.trainingPlanId, this.documentVideo.id, playbackPercentage).then((res) => {
          }).catch((e) => {
          })
        });

      }


    },


    //考试试题列表
    getTestQuestionsListForTest() {
      selectedQuestionAndScore(this.trainingPlanId).then((res) => {
        console.log(res)
        if (res.data.code === 1) {
          let code = 1; // 初始化code从1开始
          this.testQuestionList = res.data.data.map(question => {
            // 添加code属性到每个question对象
            return {
              ...question, // 展开原有的question属性
              code: code++ // 添加新的code属性，并且每次调用时递增
            };
          });
          this.ans = this.testQuestionList.reduce((acc, question) => {
            // 对于单选题和判断题，默认答案可以是一个空字符串
            // 对于多选题，默认答案应该是一个空数组
            acc[question.id] = question.type === '多选' ? [] : '';
            return acc;
          }, {});

          if (this.testQuestionList.length !== 0) {
            this.testVisible = true;
          }

        } else {
          this.testVisible = false;
          this.myScore = res.data.msg;
          this.myScoreVisible = true;
        }
      }).catch((e) => {
      })
    },
    handleChange(question) {
      this.$set(this.click, question.id, true);
      console.log(question)
    },

    validateAnswers() {
      this.$confirm("是否交卷", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let score = 0;
        let allSocre = 0;
        this.testQuestionList.forEach(question => {
          if (question.type === '单选' || question.type === '判断') {
            if (this.ans[question.id] === question.ans) {
              score += question.score;
            }
            allSocre += question.score;
          } else if (question.type === '多选') {
            let flag = true;
            // 多选题需要确保所有选项都被选中
            for (let i = 0; i < this.ans[question.id].length; i++) {
              if (!question.ans.includes(this.ans[question.id][i])) {
                flag = false;
              }
            }
            if (flag && this.ans[question.id].length === question.ans.length) {
              score += question.score;
            }
            allSocre += question.score;
          }
        });
        //alert(`你的得分是：${score}/${allSocre}`);
        addScore(this.trainingPlanId, score + "/" + allSocre).then((res) => {
          if (res.data.code === 1) {
            this.$message.success("交卷成功");
            this.testVisible = false;
            this.getTestQuestionsListForTest();
          }
        }).catch((e) => {
        })

      }).catch(() => {

      });
    },
    //点击移动
    scrollToCard(cardId) {
      // 使用ref属性来获取Vue组件实例
      const cardRef = `card-${cardId}`;
      const cardElement = this.$refs[cardRef] && this.$refs[cardRef][0]?.$el; // 获取卡片元素的 DOM 节点

      //console.log("cardElement", cardElement);

      if (cardElement) {
        // 使用scrollIntoView方法滚动到卡片位置
        cardElement.scrollIntoView({
          behavior: 'smooth', // 平滑滚动
          block: 'start', // 滚动到卡片顶部
          inline: 'nearest' // 滚动到卡片最近的边缘
        });
      }
    }


  },
  mounted() {
    this.getDocumentVideos();

  }
};
</script>


<style>
* {
  margin: 0;
  padding: 0;
}

// 标签超出宽度显示省略号
.span-ellipsis {
  width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  color: #fff;
}

.radio-group .el-radio {
  display: block; /* 使每个选项独占一行 */
  margin: 10px 0; /* 添加一些垂直间距 */
}

.radio-group {
  text-align: left; /* 左对齐单选按钮组 */
}


.checkbox-group {
  text-align: left; /* 左对齐复选框组 */
}

.checkbox-group .el-checkbox {
  display: block; /* 使每个选项独占一行 */
  margin: 10px 0; /* 添加一些垂直间距 */
}

.el-radio__original {
  display: none; /* 或者 visibility: hidden; */
}


</style>
